﻿/*  
    作者:Devil月哥
    制作日期:2012年11月13日
    文件功能:RSA加密解密已经签名获取Hash值
    修改日期:
    修改内容:
            RSA加密解密以及数字签名
            RSA加密需要公钥
            RSA解密需要私钥
            数字签名需要现将要签名的文本取值Hash,并配合私钥
            签名验证需要公钥
    遗留问题:
*/
using System;
using System.Text;
using System.Security.Cryptography;

namespace Kernel.Encrypt
{
    /// <summary>
    /// Rsa加密解密函数
    /// </summary>
    public class Rsa
    {
        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public Rsa() { }
        #endregion

        #region 生成RSA密钥
        /// <summary>
        /// 生成RSA密钥
        /// </summary>
        /// <param name="PrivateKey">私钥</param>
        /// <param name="PublicKey">公钥</param>
        public static void RSA_Produce(out string PrivateKey, out string PublicKey)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider Rsa = new RSACryptoServiceProvider();

                PrivateKey = Rsa.ToXmlString(true);

                PublicKey = Rsa.ToXmlString(false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region RSA加密(KEY必须是XML的行式,返回string)
        /// <summary>
        /// RSA加密(KEY必须是XML的行式,返回string)
        /// </summary>
        /// <param name="PublicKey">公钥</param>
        /// <param name="EncryptString">加密密文</param>
        /// <returns></returns>
        public static string RSA_Encrypt(string PublicKey, string EncryptString)
        {
            try
            {
                byte[] PlainTextBArray;

                byte[] CypherTextBArray;

                string Result;

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                rsa.FromXmlString(PublicKey);

                PlainTextBArray = (new UnicodeEncoding()).GetBytes(EncryptString);

                CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);

                Result = Convert.ToBase64String(CypherTextBArray);

                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA加密(KEY必须是XML的行式,返回string)
        /// </summary>
        /// <param name="PublicKey">公钥</param>
        /// <param name="EncryptString">加密密文</param>
        /// <returns></returns>
        public static string RSA_Encrypt(string PublicKey, byte[] EncryptString)
        {
            try
            {
                byte[] CypherTextBArray;

                string Result;

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                rsa.FromXmlString(PublicKey);

                CypherTextBArray = rsa.Encrypt(EncryptString, false);

                Result = Convert.ToBase64String(CypherTextBArray);

                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region RSA解密(KEY必须是XML的行式,返回string)
        /// <summary>
        ///  RSA解密(KEY必须是XML的行式,返回string)
        /// </summary>
        /// <param name="PrivateKey">私钥</param>
        /// <param name="EncryptString">加密密文</param>
        /// <returns></returns>
        public static string RSA_Decrypt(string PrivateKey, string EncryptString)
        {
            try
            {
                byte[] PlainTextBArray;

                byte[] DypherTextBArray;

                string Result;

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                rsa.FromXmlString(PrivateKey);

                PlainTextBArray = Convert.FromBase64String(EncryptString);

                DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);

                Result = (new UnicodeEncoding()).GetString(DypherTextBArray);

                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        ///  RSA解密(KEY必须是XML的行式,返回string)
        /// </summary>
        /// <param name="PrivateKey">私钥</param>
        /// <param name="EncryptString">加密密文</param>
        /// <returns></returns>
        public static string RSA_Decrypt(string PrivateKey, byte[] EncryptString)
        {
            try
            {
                byte[] DypherTextBArray;

                string Result;

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                rsa.FromXmlString(PrivateKey);

                DypherTextBArray = rsa.Decrypt(EncryptString, false);

                Result = (new UnicodeEncoding()).GetString(DypherTextBArray);

                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取Hash描述表
        //获取Hash描述表
        /// <summary>
        /// 获取Hash描述表
        /// </summary>
        /// <param name="m_strSource"></param>
        /// <param name="HashData"></param>
        /// <returns></returns>
        public static bool GetHash(string m_strSource, ref byte[] HashData)
        {
            try
            {
                //从字符串中取得Hash描述

                byte[] Buffer;

                System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");

                Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);

                HashData = MD5.ComputeHash(Buffer);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //获取Hash描述表
        /// <summary>
        /// 获取Hash描述表
        /// </summary>
        /// <param name="m_strSource"></param>
        /// <param name="strHashData"></param>
        /// <returns></returns>
        public static bool GetHash(string m_strSource, ref string strHashData)
        {
            try
            {
                //从字符串中取得Hash描述

                byte[] Buffer;

                byte[] HashData;

                System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");

                Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);

                HashData = MD5.ComputeHash(Buffer);

                strHashData = Convert.ToBase64String(HashData);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //获取Hash描述表

        /// <summary>
        /// 获取Hash描述表
        /// </summary>
        /// <param name="objFile"></param>
        /// <param name="HashData"></param>
        /// <returns></returns>
        public static bool GetHash(System.IO.FileStream objFile, ref byte[] HashData)
        {
            try
            {
                //从文件中取得Hash描述

                System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");

                HashData = MD5.ComputeHash(objFile);

                objFile.Close();

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //获取Hash描述表

        /// <summary>
        /// 获取Hash描述表
        /// </summary>
        /// <param name="objFile"></param>
        /// <param name="strHashData"></param>
        /// <returns></returns>
        public static bool GetHash(System.IO.FileStream objFile, ref string strHashData)
        {
            try
            {
                //从文件中取得Hash描述

                byte[] HashData;

                System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");

                HashData = MD5.ComputeHash(objFile);

                objFile.Close();

                strHashData = Convert.ToBase64String(HashData);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region RSA数字签名
        //RSA签名
        /// <summary>
        /// RSA数字签名
        /// </summary>
        /// <param name="PrivateKey">私钥</param>
        /// <param name="HashbyteSignature">Hash</param>
        /// <param name="EncryptedSignatureData"></param>
        /// <returns></returns>
        public static bool RSA_SignatureFormatter(string PrivateKey, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(PrivateKey);

                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);

                //设置签名的算法为MD5

                RSAFormatter.SetHashAlgorithm("MD5");

                //执行签名

                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //RSA签名

        /// <summary>
        /// RSA数字签名
        /// </summary>
        /// <param name="PrivateKey"></param>
        /// <param name="HashbyteSignature"></param>
        /// <param name="m_strEncryptedSignatureData"></param>
        /// <returns></returns>
        public static bool RSA_SignatureFormatter(string PrivateKey, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData)
        {
            try
            {
                byte[] EncryptedSignatureData;

                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(PrivateKey);

                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);

                //设置签名的算法为MD5

                RSAFormatter.SetHashAlgorithm("MD5");

                //执行签名

                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

                m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //RSA签名

        /// <summary>
        /// RSA数字签名
        /// </summary>
        /// <param name="PrivateKey"></param>
        /// <param name="m_strHashbyteSignature"></param>
        /// <param name="EncryptedSignatureData"></param>
        /// <returns></returns>
        public static bool RSA_SignatureFormatter(string PrivateKey, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData)
        {
            try
            {
                byte[] HashbyteSignature;

                HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);

                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(PrivateKey);

                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);

                //设置签名的算法为MD5

                RSAFormatter.SetHashAlgorithm("MD5");

                //执行签名

                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //RSA签名

        /// <summary>
        /// RSA数字签名
        /// </summary>
        /// <param name="PrivateKey"></param>
        /// <param name="m_strHashbyteSignature"></param>
        /// <param name="m_strEncryptedSignatureData"></param>
        /// <returns></returns>
        public static bool RSA_SignatureFormatter(string PrivateKey, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
        {
            try
            {
                byte[] HashbyteSignature;

                byte[] EncryptedSignatureData;

                HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);

                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(PrivateKey);

                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);

                //设置签名的算法为MD5

                RSAFormatter.SetHashAlgorithm("MD5");

                //执行签名

                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

                m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region RSA数字签名验证
        /// <summary>
        /// RSA数字签名验证
        /// </summary>
        /// <param name="PublicKey"></param>
        /// <param name="HashbyteDeformatter"></param>
        /// <param name="DeformatterData"></param>
        /// <returns></returns>
        public static bool RSA_SignatureDeformatter(string PublicKey, byte[] HashbyteDeformatter, byte[] DeformatterData)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(PublicKey);

                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);

                //指定解密的时候HASH算法为MD5

                RSADeformatter.SetHashAlgorithm("MD5");

                if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA数字签名验证
        /// </summary>
        /// <param name="PublicKey"></param>
        /// <param name="p_strHashbyteDeformatter"></param>
        /// <param name="DeformatterData"></param>
        /// <returns></returns>
        public static bool RSA_SignatureDeformatter(string PublicKey, string p_strHashbyteDeformatter, byte[] DeformatterData)
        {
            try
            {
                byte[] HashbyteDeformatter;

                HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);

                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(PublicKey);

                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);

                //指定解密的时候HASH算法为MD5

                RSADeformatter.SetHashAlgorithm("MD5");

                if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA数字签名验证
        /// </summary>
        /// <param name="PublicKey"></param>
        /// <param name="HashbyteDeformatter"></param>
        /// <param name="p_strDeformatterData"></param>
        /// <returns></returns>
        public static bool RSA_SignatureDeformatter(string PublicKey, byte[] HashbyteDeformatter, string p_strDeformatterData)
        {
            try
            {
                byte[] DeformatterData;

                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(PublicKey);

                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);

                //指定解密的时候HASH算法为MD5

                RSADeformatter.SetHashAlgorithm("MD5");

                DeformatterData = Convert.FromBase64String(p_strDeformatterData);

                if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA数字签名验证
        /// </summary>
        /// <param name="PublicKey"></param>
        /// <param name="p_strHashbyteDeformatter"></param>
        /// <param name="p_strDeformatterData"></param>
        /// <returns></returns>
        public static bool RSA_SignatureDeformatter(string PublicKey, string p_strHashbyteDeformatter, string p_strDeformatterData)
        {
            try
            {
                byte[] DeformatterData;

                byte[] HashbyteDeformatter;

                HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);

                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(PublicKey);

                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);

                //指定解密的时候HASH算法为MD5

                RSADeformatter.SetHashAlgorithm("MD5");

                DeformatterData = Convert.FromBase64String(p_strDeformatterData);

                if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
